package com.zxm.ssm.Aspect;

import com.zxm.ssm.Aspect.Interfaces.AnnotationParse;
import com.zxm.ssm.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

import static com.zxm.ssm.utils.SessionStaticMes.USER_IN_SESSION;

/**
 * @author Riskre
 * @description 权限配置AOP实现类, AOP+注解,实现权限拦截校验
 */
@Aspect
@Component
public class BrokerAspect {


    /**
     * 定义切入点，切入点为com.zxm.ssm.controller中的所有函数
     * 通过@Pointcut注解声明频繁使用的切点表达式
     */
    @Pointcut("execution(public * com.zxm.ssm.controller.*.*(..))")
    public void BrokerAspect() {

    }

    /**
     * @description 执行方法前的拦截方法
     */
    @ResponseBody
    @Around("BrokerAspect()")
    public Object doBeforeAdmin(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        //得到方法的访问权限
        final String methodAccess = AnnotationParse.privilegeParse(targetMethod);
        //如果该方法上没有权限注解，直接调用目标方法
        if (StringUtils.isBlank(methodAccess)) {
            return joinPoint.proceed();
        } else {
            //获取当前session
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpSession session = attr.getRequest().getSession(true);
            User user = (User) session.getAttribute(USER_IN_SESSION);
            System.out.println(user);
            if (user != null) {
                int role = user.getRole();
                if (role == 1) {
                    System.out.println("无管理员权限");
                    return "redirect: /ssm/user/login";
                } else {
                    return joinPoint.proceed();
                }
            }
            return null;
        }
    }

}